package com.lagou.work4;


import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class ServerThread extends Thread {
    private Socket s;

    public ServerThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        ObjectInputStream br = null;
        ObjectOutputStream ps = null;

        try {
            // 3.使用输入输出流进行通信
            br = new ObjectInputStream(s.getInputStream());
            ps = new ObjectOutputStream(s.getOutputStream());

            while(true) {
                // 实现对客户端发来对象内容的接收并打印
                // 当没有数据发来时，下面的方法会形成阻塞
                UserMessage userMessage = (UserMessage) br.readObject();
                InetAddress inetAddress = s.getInetAddress();
                User user = userMessage.getUser();
                System.out.println("客户端" + inetAddress + "发来的对象用户名是：" + user.getUserName() + ",密码是:" + user.getPassword());
                // 实现服务器向客户端回发对象内容"I received!"
                if ("admin".equals(user.getUserName())&&"123456".equals(user.getPassword())){
                    userMessage.setType("success");
                    ps.writeObject(userMessage);
                    System.out.println("客户端" + inetAddress + "已下线！");
                    break;
                }
                userMessage.setType("fail");
                ps.writeObject(userMessage);
                System.out.println("服务器发送数据成功！");
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != ps) {
                try {
                    ps.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
